﻿using DingTalk.Api;
using DingTalk.Api.Request;
using DingTalk.Api.Response;
using GBT.Entity;
using GBT.IBusiness;
using GBT.Util;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace GBT.Business.DDApi
{
    public class DDApi : IDDApi
    {

        #region accessToken
        public OapiGettokenResponse GetAccessToken()
        {
            DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.Appkey = DDApiDTO.AppKey;
            request.Appsecret = DDApiDTO.AppSecret;
            request.SetHttpMethod("GET");
            OapiGettokenResponse response = client.Execute(request);
            if (response.AccessToken == null)
            {
                throw new Exception(response.Errmsg);
            }
            return response;
        }
        #endregion

        #region 私有方法 获取用户或部门信息
        private OapiUserGetDeptMemberResponse GetUserIds(string deptId, string accessToken)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getDeptMember");
            OapiUserGetDeptMemberRequest req = new OapiUserGetDeptMemberRequest();
            req.DeptId = deptId;
            req.SetHttpMethod("GET");
            OapiUserGetDeptMemberResponse rsp = client.Execute(req, accessToken);
            if (rsp.Errmsg != "ok")
            {
                throw new Exception(rsp.Errmsg);
            }
            return rsp;
        }

        private List<OapiUserGetResponse> GetUserList(string deptId, string accessToken)
        {
            var rsp = GetUserIds(deptId, accessToken);
            List<OapiUserGetResponse> userGetuserinfoResponses = null;
            OapiUserGetResponse oapiUserGetuserinfoRequest = new OapiUserGetResponse();
            rsp?.UserIds?.ForEach(t =>
            {
                if (userGetuserinfoResponses == null)
                    userGetuserinfoResponses = new List<OapiUserGetResponse>();

                oapiUserGetuserinfoRequest = GetUser(t, accessToken);

                if (oapiUserGetuserinfoRequest != null)
                    userGetuserinfoResponses.Add(oapiUserGetuserinfoRequest);
            });
            return userGetuserinfoResponses;
        }

        /// <summary>
        /// 获取部门详情
        /// </summary>
        /// <param name="departmentId"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        private OapiDepartmentGetResponse GetDepartment(string departmentId, string accessToken)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/get");
            OapiDepartmentGetRequest request = new OapiDepartmentGetRequest();
            request.Id = departmentId;
            request.SetHttpMethod("GET");
            OapiDepartmentGetResponse response = client.Execute(request, accessToken);
            if (response.Errmsg != "ok")
            {
                throw new Exception(response.Errmsg);
            }
            return response;
        }
        #endregion

        #region 公有方法（对外） 获取部门和用户详细信息
        public List<OapiDepartmentGetResponse> GetDepartmentList(string accessToken)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
            OapiDepartmentListRequest request = new OapiDepartmentListRequest();
            request.Id = "1";
            request.FetchChild = true;
            request.SetHttpMethod("GET");
            OapiDepartmentListResponse response = client.Execute(request, accessToken);
            if (response.Errmsg != "ok")
            {
                throw new Exception(response.Errmsg);
            }
            List<OapiDepartmentGetResponse> departmentList = new List<OapiDepartmentGetResponse>();
            if (response.Department != null)
            {
                //添加一个跟部门
                response.Department.Add(new OapiDepartmentListResponse.DepartmentDomain
                {
                    Id = 1,
                });
                List<OapiDepartmentListResponse.DepartmentDomain> departments = response.Department;

                departments.ForEach(t =>
                {
                    OapiDepartmentGetResponse responseDept = GetDepartment(t.Id.ToString(), accessToken);
                    departmentList.Add(responseDept);
                });
            }
            return departmentList;
        }

        public OapiUserGetResponse GetUser(string userId, string accessToken)
        {
            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
            OapiUserGetRequest request = new OapiUserGetRequest();
            request.Userid = userId;
            request.SetHttpMethod("GET");
            OapiUserGetResponse response = client.Execute(request, accessToken);
            if (response.Errmsg != "ok")
            {
                throw new Exception(response.Errmsg);
            }
            return response;
        }

        public List<OapiUserGetResponse> GetAllUserList()
        {
            string accessToken = GetAccessToken().AccessToken;
            var deptList = GetDepartmentList(accessToken);
            List<OapiUserGetResponse> oapiUserGetResponses = new List<OapiUserGetResponse>();
            List<OapiUserGetResponse> oapiUserGetResponsesRange = new List<OapiUserGetResponse>();
            if (deptList != null)
            {
                deptList.ForEach(t =>
                {
                    oapiUserGetResponsesRange = GetUserList(t.Id.ToString(), accessToken);
                    if(oapiUserGetResponsesRange != null)
                        oapiUserGetResponses.AddRange(oapiUserGetResponsesRange);
                });
            }
            return oapiUserGetResponses;
        }

        #endregion

        #region 发送消息通知
        public OapiMessageCorpconversationAsyncsendV2Response SendMessage(string userId, string message)
        {
            string accessToken = GetAccessToken().AccessToken;

            IDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");

            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.UseridList = userId;
            request.AgentId = DDApiDTO.AgentId;
            request.ToAllUser = false;

            OapiMessageCorpconversationAsyncsendV2Request.MsgDomain msg = new OapiMessageCorpconversationAsyncsendV2Request.MsgDomain();
            msg.Msgtype = "link";
            msg.Link = new OapiMessageCorpconversationAsyncsendV2Request.LinkDomain();
            msg.Link.Title = "【阿米巴】审批通知";
            msg.Link.Text = message;
            msg.Link.MessageUrl = "http://amb.qisisw.com/";
            msg.Link.PicUrl = "http://amb.qisisw.com/logo.png";
            request.Msg_ = msg;

            OapiMessageCorpconversationAsyncsendV2Response response = client.Execute(request, accessToken);
            return response;
        }
        #endregion
    }
}
